package com.qkl.xiatang.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.cache.LocalCacheBuilder;
import com.qkl.xiatang.app.cache.LocalSimpleCache;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.log.JobLogTitleDTO;
import com.qkl.xiatang.app.entity.ConfigureEntity;
import com.qkl.xiatang.app.entity.feed.FeedAllocConfig;
import com.qkl.xiatang.app.entity.feed.FeedAllocConfigTemplate;
import com.qkl.xiatang.app.entity.feed.JobLogConfigEntity;
import com.qkl.xiatang.app.entity.pond.PondConfigEntity;
import com.qkl.xiatang.app.mapper.*;
import com.qkl.xiatang.app.utils.AppSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
@Slf4j
public class ConfigService {

    @Autowired
    private FeedAllocConfigMapper feedAllocConfigMapper;

    @Autowired
    private PondManagerService pondManagerService;

    @Autowired
    private ConfigMapper configMapper;

    @Autowired
    private PondConfigMapper pondConfigMapper;

    @Autowired
    private JobLogConfigMapper jobLogConfigMapper;

    @Autowired
    private ConfigureMapper configureMapper;

    @Autowired
    private FeedAllocConfigTemplateMapper feedAllocConfigTemplateMapper;

    private LocalSimpleCache<Map<String,Map<Integer, FeedAllocConfig>>> feedAllocConfigCache;

    private LocalSimpleCache<Map<String,Map<String, PondConfigEntity>>> pondConfigCache;

    private LocalSimpleCache<List<JobLogTitleDTO>> jobLogConfigCache;

    @PostConstruct
    public void initCache(){
        LocalCacheBuilder<Map<String,Map<Integer, FeedAllocConfig>>>  feedAllocbuilder = new LocalCacheBuilder<>();
        feedAllocConfigCache = feedAllocbuilder.build(30,null,()-> feedAllocConfig());

        LocalCacheBuilder<Map<String,Map<String, PondConfigEntity>>>pondConfigBuilder = new LocalCacheBuilder<>();
        pondConfigCache = pondConfigBuilder.build(30,null,()-> pondConfig());

        LocalCacheBuilder<List<JobLogTitleDTO>> jobConfigBuilder = new LocalCacheBuilder<>();
        jobLogConfigCache = jobConfigBuilder.build(30,null,()-> getJobLogTitle());
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<FeedAllocConfig> getFeedAllocConfigList(){
        String companyId = AppSessionUtils.getCompanyId();
        List<FeedAllocConfig> list = new ArrayList<>();
        Map<String,Map<Integer, FeedAllocConfig>> configCache = feedAllocConfigCache.getCache();
        if(ObjectUtils.isNotEmpty(configCache)){
            Map<Integer, FeedAllocConfig> allocConfigMap = configCache.get(companyId);
            /**
            if(ObjectUtils.isEmpty(allocConfigMap)){
                this.addFeedAllocConfig(companyId);
                feedAllocConfigCache.refreshCache();
                configCache = feedAllocConfigCache.getCache();
                allocConfigMap = configCache.get(companyId);
            }
             **/
            if(ObjectUtils.isNotEmpty(allocConfigMap)){
                /**
                Collection<FeedAllocConfig> collection = allocConfigMap.values();
                if(ObjectUtils.isNotEmpty(collection)){
                    list.addAll(collection);
                }
                 **/
                if(null != allocConfigMap.get(1)) {
                    list.add(allocConfigMap.get(1));
                }
                if(null != allocConfigMap.get(2)) {
                    list.add(allocConfigMap.get(2));
                }
                if(null != allocConfigMap.get(3)) {
                    list.add(allocConfigMap.get(3));
                }
            }
        }
        return list;
    }

    /**
     * 配置查料时间
     * @param checkTime 分钟
     * @param groupIdList
     * @return
     */
    public BusinessDTO<Object> configCheckFeedTime(Integer checkTime, List<String> groupIdList){
        List<String> pondIdList = pondManagerService.queryPondIdByGroup(groupIdList);
        if(ObjectUtils.isEmpty(pondIdList)){
            return BusinessDTO.failBusiness("数据异常");
        }
        configMapper.addPondConfig(AppSessionUtils.getCompanyId(),checkTime,pondIdList);
        pondConfigCache.refreshCache();
        return BusinessDTO.sucessBusiness(new HashMap<>(),"配置查料时间");
    }

    public int getCheckFeedTime(String pondId){
        if(StringUtils.isNotEmpty(pondId)) {
            Map<String, Map<String, PondConfigEntity>> cacheMap = pondConfigCache.getCache();
            if (ObjectUtils.isNotEmpty(cacheMap)) {
                Map<String, PondConfigEntity> configEntityMap = cacheMap.get(AppSessionUtils.getCompanyId());
                if (ObjectUtils.isNotEmpty(configEntityMap)) {
                    PondConfigEntity configEntity = configEntityMap.get(pondId);
                    if (null != configEntity && null != configEntity.getCheckSepar()) {
                        return configEntity.getCheckSepar();
                    }
                }
            }
        }
        return 60;
    }

    /**
     * 查询工作日志表头
     * @return
     */
    public List<JobLogTitleDTO> queryJobLogTitle(){
        List<JobLogTitleDTO> jobLogTitleList = new ArrayList<>();
        jobLogTitleList.addAll(jobLogConfigCache.getCache());
        return jobLogTitleList;
    }

    public List<ConfigureEntity> getConfigureList(String configKey){
        return configureMapper.selectList(new QueryWrapper<ConfigureEntity>().eq("config_key",configKey));
    }

    public String getConfigureValue(String configKey){
        List<ConfigureEntity> configList = this.getConfigureList(configKey);
        String value = "";
        if(ObjectUtils.isNotEmpty(configList)){
            value = StringUtils.trimToEmpty(configList.get(0).getConfigValue());
        }
        return value;
    }

    /**
     * app用户默认头像
     * @return
     */
    public String getAppUserImage(){
        return this.getConfigureValue("app_user_head_image");
    }


    /**
     * 消息推送url
     * @return
     */
    public String messagePushUrl(){
        return this.getConfigureValue("message_push_url");
    }

    /**
     * 消息推送跳转路径
     * @return
     */
    public String messagePushDataUrl(){
        return this.getConfigureValue("message_push_data_url");
    }

    /**
     * 上传url
     * @return
     */
    public String uploadFileUrl(){
        return this.getConfigureValue("upload_file_url");
    }


    private List<JobLogTitleDTO> getJobLogTitle(){
        List<JobLogTitleDTO> list = new ArrayList<>();
        List<JobLogConfigEntity> entities = jobLogConfigMapper.selectList(new QueryWrapper<JobLogConfigEntity>().last("ORDER BY sort"));
        if(ObjectUtils.isNotEmpty(entities)){
            for(JobLogConfigEntity entity:entities){
                JobLogTitleDTO dto = new JobLogTitleDTO();
                dto.setKey(entity.getId());
                dto.setName(entity.getName());
                list.add(dto);
            }
        }
        return list;
    }

    private Map<String,Map<String, PondConfigEntity>> pondConfig(){
        Map<String,Map<String, PondConfigEntity>> retMap = new HashMap<>();
        List<PondConfigEntity>  list = pondConfigMapper.selectList(null);
        if(ObjectUtils.isNotEmpty(list)){
            for (PondConfigEntity config : list){
                String companyId = config.getCompanyId();
                if(!retMap.containsKey(companyId)){
                    retMap.put(companyId,new HashMap<>());
                }
                retMap.get(companyId).put(config.getPondId(),config);
            }
        }
        return retMap;
    }

    private Map<String,Map<Integer, FeedAllocConfig>> feedAllocConfig(){
        Map<String,Map<Integer, FeedAllocConfig>> retMap = new HashMap<>();
        List<FeedAllocConfig>  list = feedAllocConfigMapper.selectList(null);
        log.info("======== feedAllocConfig list={}",list);
        if(ObjectUtils.isNotEmpty(list)){
            for (FeedAllocConfig config : list){
                String companyId = config.getCompanyId();
                if(!retMap.containsKey(companyId)){
                    retMap.put(companyId,new HashMap<>());
                }
                retMap.get(companyId).put(config.getSerialNo(),config);
            }
        }
        return retMap;
    }

    public void addFeedAllocConfig(String companyId){
        List<FeedAllocConfigTemplate> templateList = this.queryAllocConfigTemplate();
        if(ObjectUtils.isEmpty(templateList)){
            return;
        }
        for (FeedAllocConfigTemplate template : templateList){
            this.addFeedAllocConfig(template,companyId);
        }
    }

    public void addFeedAllocConfig(FeedAllocConfigTemplate template,String companyId){
        try {
            FeedAllocConfig config = new FeedAllocConfig();
            config.setName(template.getName());
            config.setCompanyId(companyId);
            config.setCreateTime(new Date());
            config.setEndHour(template.getEndHour());
            config.setQuerySeparTime(template.getQuerySeparTime());
            config.setSerialNo(template.getSerialNo());
            config.setStartHour(template.getStartHour());
            config.setSort(template.getSort());
            feedAllocConfigMapper.insert(config);
        }catch (Exception e){

        }
    }

    private List<FeedAllocConfigTemplate> queryAllocConfigTemplate(){
        return feedAllocConfigTemplateMapper.selectList(null);
    }

}
